package com.itheima.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Time;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Calendar;
import java.util.Map;
import java.util.Set;

public class ClearImgJob {

    @Autowired
    JedisPool jedisPool;

    @Reference
    private OrderSettingService orderSettingService;

    /**
     * 步骤：
     *      1.获取两个set集合的差值
     *      2.遍历
     *          删除七牛云上的垃圾图片
     *          删除redis上的垃圾图片
     */
    public void clear(){
        // sdiff : 获取两个集合的差值。得到的就是垃圾图片
        Set<String> imgNames = jedisPool.getResource().sdiff(RedisConst.SETMEAL_PIC_RESOURCES, RedisConst.SETMEAL_PIC_DB_RESOURCES);

        for (String imgName : imgNames) {
            QiniuUtils.deleteFileFromQiniu(imgName);
            jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES,imgName);
        }

        System.out.println("您删除的垃圾图片是：" + imgNames);

    }

    /**
     * 定时删除数据
     * @throws Exception
     */
    public void Delete() throws Exception {
        //查找时间
        Time time = orderSettingService.findMonth();

        Integer month = time.getMonth();
        Integer date = time.getDate();
        //创建日历
        Calendar calendar = Calendar.getInstance();
        //如果有月有日
        if (date!=null&&month!=null){
            calendar.add(Calendar.MONTH,-month);
            String str = DateUtils.parseDate2String(calendar.getTime(),"yyyy-MM");
            str += "-"+date;
            orderSettingService.JobDelete(str);
        }
        //如果有月没有日
        if (date==null&&month!=null){
            calendar.add(Calendar.MONTH,-month);
            String str = DateUtils.parseDate2String(calendar.getTime(),"yyyy-MM");
            str += "-1";
            orderSettingService.JobDelete(str);
        }
        //如果有日没有月
        if (date!=null&&month==null){
            //每个月的指定日清理
            String str = DateUtils.parseDate2String(calendar.getTime(),"yyyy-MM");
            str += "-"+date;
            orderSettingService.JobDelete(str);
        }

        System.out.println("定时清理数据成功");


    }


}
